/*---------------------------------------------------------------------------
 * Speculoos, LDAP to objet mapping.
 * Copyright (C) 2006  Norsys and OQube
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Created on Oct 20, 2005
 * --------------------------------------------------------------------------*/
package speculoos.commons.mockldap;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TestDirContextFactory implements InitialContextFactory {

    public static final String TESTSOURCE = "speculoos.commons.mockldap.testsource";

    private static ThreadLocal instance = new ThreadLocal();
    private static ThreadLocal instanceSrc = new ThreadLocal();
    
    private final Log log = LogFactory.getLog(TestDirContextFactory.class);

    public Context getInitialContext(Hashtable arg0) throws NamingException {
        /* find file */
        String src = (String) arg0.get(TESTSOURCE);
        if (src == null)
            throw new NamingException("no test file given");        
        String instanceSrcVal = (String) instanceSrc.get();
        if (instanceSrcVal != null && instanceSrcVal.equals(src)) {
        	return (Context) instance.get();
        } else { 
	        LDIFParser p = new LDIFParser();
	        try {
	            log.info("Parsing LDIF file "+src);
	            /* extract stream from ressource  name */
	            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(src);
	            Context root = p.parse(is);
	            instance.set(root);
	            instanceSrc.set(src);
	            log.info("Done parsing LDIF file :" +p.getEntryCount()+" entries in root node "+root.getNameInNamespace());
	            return root;
	        } catch (IOException e) {
	            throw new NamingException("I/O error :" + e.getLocalizedMessage());
	        }
        }
    }

}
